<template>
  <div class="post-editor-container">
    <div class="post-editor-card">
      <header class="post-editor-header">
        <div class="header-content">
          <h1>发布新帖子</h1>
          <div class="header-actions">
            <el-button class="cancel-btn" @click="cancelPost">取消</el-button>
            <el-button type="primary" class="submit-btn" @click="submitPost">发布</el-button>
          </div>
        </div>
        <div class="header-divider"></div>
      </header>

      <main class="post-editor-main">
        <el-form :model="postForm" label-width="100px" class="post-form">
         <el-form-item label="科目" required>
                <el-select 
                v-model="postForm.courseId" 
                placeholder="请选择科目" 
                @change="handleCourseChange"
                class="large-form-select"
                popper-class="large-select-dropdown"
                >
                <el-option
                    v-for="item in courseList"
                    :key="item.courseId"
                    :label="item.courseName"
                    :value="item.courseId"
                ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="题目" required>
                <el-select 
                v-model="postForm.questionId" 
                placeholder="请先选择科目" 
                :disabled="!questionList.length"
                class="large-form-select"
                popper-class="large-select-dropdown"
                >
                <el-option
                    v-for="item in questionList"
                    :key="item.questionId"
                    :label="item.content"
                    :value="item.questionId"
                />
                </el-select>
            </el-form-item>

          <el-form-item label="标题" required>
            <input
              v-model="postForm.title"
              maxlength="50"
              placeholder="请输入帖子标题（50字以内）"
              class="title-input el-input__inner"
              style="width: 100%; height: 44px; line-height: 44px; border-radius: 8px; border: 1px solid #d0d7de; font-size: 16px; padding: 0 15px;"
            >
            <div style="text-align: right; color: #aaa; font-size: 13px; margin-top: 2px;">
              {{ postForm.title.length }}/50
            </div>
          </el-form-item>

          <el-form-item label="内容" required class="post-content-item">
            <div class="editor-container">
              <div class="toolbar">
                <button type="button" @click="execCommand('bold')" title="加粗" class="toolbar-btn">
                  <i class="icon-bold"></i>
                </button>
                <button type="button" @click="execCommand('italic')" title="斜体" class="toolbar-btn">
                  <i class="icon-italic"></i>
                </button>
                <button type="button" @click="execCommand('underline')" title="下划线" class="toolbar-btn">
                  <i class="icon-underline"></i>
                </button>
                <div class="divider"></div>
                
                <!-- 字体选择 -->
            <el-popover
            placement="bottom"
            width="200"
            trigger="click"
            >
            <div class="font-family-panel">
                <div 
                v-for="font in fontOptions"
                :key="font.value"
                class="font-option"
                :style="{ fontFamily: font.value }"
                @click="setFontFamily(font.value)"
                >
                {{ font.label }}
                </div>
            </div>
            <template #reference>
              <button type="button" title="字体" class="toolbar-btn">
                <i class="icon-font-family"></i>
              </button>
            </template>
            </el-popover>
            
            <!-- 字号选择 -->
            <el-popover
            placement="bottom"
            width="120"
            trigger="click"
            >
            <div class="font-size-panel">
                <div 
                v-for="size in sizeOptions"
                :key="size"
                class="size-option"
                @click="setFontSize(size)"
                >
                {{ size }}
                </div>
            </div>
            <template #reference>
              <button type="button" title="字号" class="toolbar-btn">
                <i class="icon-font-size"></i>
              </button>
            </template>
            </el-popover>
                
                <el-color-picker
                v-model="fontColor"
                @change="setFontColor"
                class="toolbar-color-picker"
                show-alpha
                :predefine="predefineColors"
                />
                
                <div class="divider"></div>
                
                <!-- 对齐和缩进 -->
                <button type="button" @click="setTextAlign('left')" title="居左对齐" class="toolbar-btn">
                <i class="icon-align-left"></i>
                </button>
                <button type="button" @click="setTextAlign('center')" title="居中对齐" class="toolbar-btn">
                <i class="icon-align-center"></i>
                </button>
                <button type="button" @click="setTextAlign('right')" title="居右对齐" class="toolbar-btn">
                <i class="icon-align-right"></i>
                </button>
                
                <button type="button" @click="execCommand('indent')" title="增加缩进" class="toolbar-btn">
                <i class="icon-indent"></i>
                </button>
                <button type="button" @click="execCommand('outdent')" title="减少缩进" class="toolbar-btn">
                <i class="icon-outdent"></i>
                </button>
                
                <div class="divider"></div>
                
                <!-- 列表 -->
                <button type="button" @click="execCommand('insertUnorderedList')" title="无序列表" class="toolbar-btn">
                <i class="icon-list-ul"></i>
                </button>
                <button type="button" @click="execCommand('insertOrderedList')" title="有序列表" class="toolbar-btn">
                <i class="icon-list-ol"></i>
                </button>
                
                <!-- 表格 -->
                <el-popover
                placement="bottom"
                width="200"
                trigger="click"
                >
                <div class="table-grid">
                    <div 
                    v-for="row in 5" 
                    :key="'row-'+row" 
                    class="table-grid-row"
                    >
                    <div 
                        v-for="col in 5" 
                        :key="'col-'+col" 
                        class="table-grid-cell"
                        @click="insertTable(row, col)"
                        @mouseover="hoverTableSize = `${row}x${col}`"
                    ></div>
                    </div>
                </div>
                <div class="table-size-hint">{{ hoverTableSize }}</div>
                <template #reference>
                  <button type="button" title="插入表格" class="toolbar-btn">
                    <i class="icon-table"></i>
                  </button>
                </template>
                </el-popover>
                
                <!-- 特殊字符 -->
                <el-popover
                placement="bottom"
                width="300"
                trigger="click"
                >
                <div class="special-chars-grid">
                    <button
                    v-for="(char, index) in specialChars"
                    :key="index"
                    class="char-btn"
                    @click="insertSpecialChar(char)"
                    >
                    {{ char }}
                    </button>
                </div>
                <template #reference>
                  <button type="button" title="特殊字符" class="toolbar-btn">
                    <i class="icon-special-char"></i>
                  </button>
                </template>
                </el-popover>
                
                <!-- 清除格式 -->
                <button type="button" @click="clearFormatting" title="清除格式" class="toolbar-btn">
                <i class="icon-clear-format"></i>
                </button>
                
                <div class="divider"></div>
                
                <!-- 链接和图片 -->
                <button type="button" @click="execCommand('createLink', prompt('请输入链接地址:'))" title="插入链接" class="toolbar-btn">
                  <i class="icon-link"></i>
                </button>
                <button type="button" @click="insertImage" title="插入图片" class="toolbar-btn">
                  <i class="icon-image"></i>
                </button>
            </div>
              <div 
                ref="postEditor" 
                class="editor" 
                contenteditable="true" 
                @input="updatePostContent"
                placeholder="在这里输入内容..."
              ></div>
            </div>
            <div class="editor-footer">
              <span class="word-count" v-if="postForm.content">{{ postForm.content.length }}字</span>
              <span class="placeholder-tip">支持文本、图片、链接等内容</span>
            </div>
          </el-form-item>
        </el-form>
      </main>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '../../../store/UserStore'
import axios from 'axios'

export default {
  data() {
    return {
      postForm: {
        title: '',
        content: '',
        courseId: null,
        questionId: null,
      },
      courseList: [],
      questionList: [],
      userStore: useUserStore(),
      fontFamily: '',
      fontSize: '',
      fontColor: '',
      hoverTableSize: '0x0',
      fontOptions: [
        { label: '默认', value: '' },
        { label: '宋体', value: 'SimSun' },
        { label: '黑体', value: 'SimHei' },
        { label: '微软雅黑', value: 'Microsoft YaHei' },
        { label: 'Arial', value: 'Arial' },
        { label: 'Times New Roman', value: 'Times New Roman' },
        { label: 'Courier New', value: 'Courier New' }
      ],
      sizeOptions: ['12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px', '36px'],
      predefineColors: [
        '#000000', '#ffffff', '#ff0000', '#00ff00', '#0000ff', 
        '#ffff00', '#00ffff', '#ff00ff', '#c0c0c0', '#808080'
      ],
      specialChars: [
        '©', '®', '™', '€', '$', '£', '¥', '§', '¶', '•',
        '←', '↑', '→', '↓', '↔', '⇐', '⇑', '⇒', '⇓', '⇔',
        'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'λ', 'μ',
        '≠', '≈', '≤', '≥', '±', '×', '÷', '∞', '√', '∫',
        '♠', '♣', '♥', '♦', '★', '☆', '☀', '☁', '☂', '☃'
      ]
    }
    },

  methods: {
    insertImage() {
      const url = prompt('请输入图片地址:')
      if (url) {
        this.execCommand('insertImage', url)
      }
    },
    execCommand(command, value = null) {
      document.execCommand(command, false, value)
      this.$refs.postEditor.focus()
    },
    updatePostContent() {
      this.postForm.content = this.$refs.postEditor.innerHTML
    },
    async fetchCourseList() {
      try {
        const response = await axios.get('http://localhost:8080/Courses/all')
        this.courseList = response.data || []
      } catch (error) {
        console.error('获取课程列表失败:', error)
        this.$message.error('获取课程列表失败')
      }
    },
    async handleCourseChange(courseId) {
      this.postForm.questionId = null
      if (!courseId) {
        this.questionList = []
        return
      }
      try {
        const response = await axios.get('http://localhost:8080/question/by-course', {
          params: { courseId }
        })
        this.questionList = response.data || []
      } catch (error) {
        console.error('获取题目列表失败:', error)
        this.$message.error('获取题目列表失败')
      }
    },
    async submitPost() {
      if (!this.postForm.title || !this.postForm.content || !this.postForm.courseId || !this.postForm.questionId) {
        this.$message.warning('请填写完整信息');
        return;
      }
      
      const sanitizedContent = this.sanitizeHtml(this.postForm.content);
      
      const userId = this.userStore.getUserInfo?.userId;
      if (!userId) {
        this.$message.error('请先登录');
        return;
      }
      
      const postData = {
        userId: userId,
        title: this.postForm.title,
        content: sanitizedContent,
        courseId: this.postForm.courseId,
        questionId: this.postForm.questionId
      };
      
      try {
        await axios.post('http://localhost:8080/topic/add', postData);
        this.$message.success('发帖成功');
        this.$router.push('/home/user-communication');
      } catch (error) {
        console.error('发帖失败:', error);
        this.$message.error('发帖失败，请稍后重试');
      }
    },
    sanitizeHtml(html) {
      if (!html) return ''
      return html
        .replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
        .replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, (match) => {
          const allowedTags = ['b', 'i', 'u', 'strong', 'em', 'p', 'br', 'ul', 'ol', 'li', 'div', 'span', 'img', 'a']
          const tagMatch = match.match(/<\/?(\w+)/)
          if (tagMatch && allowedTags.includes(tagMatch[1].toLowerCase())) {
            return match
          }
          return ''
        })
    },
    cancelPost() {
      this.$router.go(-1)
    },
    setTextAlign(align) {
      this.execCommand('justifyLeft') // 先清除现有对齐
      this.execCommand('justifyRight') // 先清除现有对齐
      this.execCommand('justifyCenter') // 先清除现有对齐
      
      // 设置新的对齐方式
      switch(align) {
        case 'left':
          this.execCommand('justifyLeft')
          break
        case 'center':
          this.execCommand('justifyCenter')
          break
        case 'right':
          this.execCommand('justifyRight')
          break
      }
      this.$refs.postEditor.focus()
    },
    setFontFamily(family) {
      this.execCommand('fontName', family || '')
      this.$refs.postEditor.focus()
    },
    setFontSize(size) {
      this.execCommand('fontSize', size ? '7' : '3') // 7是最大的字号
      if (size) {
        // 设置具体的字体大小
        const element = document.createElement('span')
        element.style.fontSize = size
        this.execCommand('formatBlock', element.outerHTML)
      }
      this.$refs.postEditor.focus()
    },
    setFontColor(color) {
      this.execCommand('foreColor', color || '#000000')
      this.$refs.postEditor.focus()
    },
    insertTable(rows, cols) {
      let tableHtml = '<table border="1" style="width:100%;border-collapse:collapse;">'
      for (let i = 0; i < rows; i++) {
        tableHtml += '<tr>'
        for (let j = 0; j < cols; j++) {
          tableHtml += `<td style="padding:5px;">&nbsp;</td>`
        }
        tableHtml += '</tr>'
      }
      tableHtml += '</table>'

      this.execCommand('insertHTML', tableHtml)
      this.$refs.postEditor.focus()
    },
    insertSpecialChar(char) {
      this.execCommand('insertText', char)
      this.$refs.postEditor.focus()
    },
    clearFormatting() {
      this.execCommand('removeFormat');
      this.execCommand('unlink');
      // 额外去除选区内的 style 属性
      const selection = window.getSelection();
      if (selection && selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);
        const fragment = range.cloneContents();
        // 创建一个临时div用于处理
        const tempDiv = document.createElement('div');
        tempDiv.appendChild(fragment);
        // 移除所有 style 属性
        tempDiv.querySelectorAll('[style]').forEach(el => el.removeAttribute('style'));
        // 替换选区内容
        range.deleteContents();
        range.insertNode(document.createTextNode(tempDiv.textContent));
      }
      this.$refs.postEditor.focus();
    }
  },
  async mounted() {
    await this.fetchCourseList()
    this.$nextTick(() => {
      this.$refs.postEditor.focus()
    })
  }
}
</script>

<style scoped lang="scss">
.large-form-select {
  width: 100%;
  
  :deep(.el-input__inner) {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    padding: 0 15px;
  }
  
  :deep(.el-input__icon) {
    line-height: 48px;
  }
}
.post-editor-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #d0ecfe 100%;
  min-height: calc(100vh - 40px);
}

.post-editor-card {
  width: 100%;
  max-width: 900px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.post-editor-header {
  padding: 20px 30px 0;
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    h1 {
      font-size: 22px;
      color: #333;
      font-weight: 600;
      margin: 0;
    }
  }
  
  .header-divider {
    height: 1px;
    background: linear-gradient(to right, #f0f2f5, #d0d7de, #f0f2f5);
  }
}

.header-actions {
  display: flex;
  gap: 12px;
  
  .cancel-btn {
    border-color: #d0d7de;
    color: #666;
    &:hover {
      background-color: #f8f9fa;
    }
  }
  
  .submit-btn {
    background-color: #1e88e5;
    border-color: #1e88e5;
    &:hover {
      background-color: #1976d2;
      border-color: #1976d2;
    }
  }
}

.post-editor-main {
  padding: 20px 30px 30px;
  
  .post-form {
    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #555;
      padding-right: 20px;
    }
  }
}

.form-select, .title-input {
  width: 100%;
  
  :deep(.el-input__inner) {
    height: 44px;
    line-height: 44px;
    border-radius: 8px;
    border: 1px solid #d0d7de;
    transition: all 0.3s;
    
    &:hover {
      border-color: #a0aec0;
    }
    
    &:focus {
      border-color: #1e88e5;
      box-shadow: 0 0 0 2px rgba(30, 136, 229, 0.2);
    }
  }
}

// 让富文本容器宽度与输入框一致
.editor-container {
  border: 1px solid #d0d7de;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  
  &:hover {
    border-color: #a0aec0;
  }
  
  &:focus-within {
    border-color: #1e88e5;
    box-shadow: 0 0 0 2px rgba(30, 136, 229, 0.2);
  }
}

.editor {
  min-height: 500px;
  padding: 24px;
  outline: none;
  overflow-y: auto;
  line-height: 1.8;
  font-size: 16px;
  color: #333;
  background-color: #fff;
  width: 100%;
  box-sizing: border-box;
  
  &:empty:before {
    content: attr(placeholder);
    color: #a0aec0;
    display: block;
  }
  
  img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 10px 0;
  }
  
  a {
    color: #1e88e5;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
  
  ul, ol {
    padding-left: 24px;
    margin: 10px 0;
  }
}

.toolbar {
  background: #f8f9fa;
  padding: 10px 15px;
  border-bottom: 1px solid #eaeef2;
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.toolbar-btn {
  background: transparent;
  border: none;
  border-radius: 4px;
  padding: 6px 8px;
  cursor: pointer;
  color: #555;
  transition: all 0.2s;
  
  &:hover {
    background-color: #eaeef2;
    color: #1e88e5;
  }
  
  i {
    display: block;
    width: 18px;
    height: 18px;
    font-style: normal;
    text-align: center;
    line-height: 18px;
  }
}

.divider {
  width: 1px;
  height: 24px;
  background: #eaeef2;
  margin: 0 3px;
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 13px;
  color: #a0aec0;
  
  .word-count {
    color: #666;
  }
}

/* 下拉菜单样式 */
:global(.select-dropdown) {
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12) !important;
  border: none !important;
  
  .el-select-dropdown__item {
    height: 40px;
    line-height: 40px;
    padding: 0 15px;
    
    &:hover {
      background-color: #f5f7fa;
    }
    
    &.selected {
      color: #1e88e5;
      font-weight: normal;
      background-color: #f0f7ff;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .post-editor-container {
    padding: 10px;
  }
  
  .post-editor-card {
    border-radius: 8px;
  }
  
  .post-editor-header,
  .post-editor-main {
    padding: 15px 20px;
  }
  
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .editor {
    min-height: 300px;
    padding: 15px;
  }
}

@media (max-width: 480px) {
  .post-editor-main {
    padding: 15px;
  }
  
  .post-form {
    :deep(.el-form-item__label) {
      width: 80px !important;
    }
    
    :deep(.el-form-item__content) {
      margin-left: 80px !important;
    }
  }
  
  .editor {
    min-height: 250px;
  }
}

/* 工具栏图标样式 */
.icon-bold:before {
  content: "B";
  font-weight: bold;
}

.icon-italic:before {
  content: "I";
  font-style: italic;
}

.icon-underline:before {
  content: "U";
  text-decoration: underline;
}

.icon-align-left:before {
  content: "≡";
  font-weight: bold;
  display: inline-block;
  transform: rotate(90deg);
}

.icon-align-center:before {
  content: "≡";
  font-weight: bold;
}

.icon-align-right:before {
  content: "≡";
  font-weight: bold;
  display: inline-block;
  transform: rotate(-90deg);
}

.icon-indent:before {
  content: "↳";
  transform: rotate(90deg);
  display: inline-block;
}

.icon-outdent:before {
  content: "↳";
  transform: rotate(-90deg);
  display: inline-block;
}

.icon-list-ul:before {
  content: "•";
  font-size: 18px;
}

.icon-list-ol:before {
  content: "1.";
  font-size: 14px;
}

.icon-table:before {
  content: "田";
  font-size: 14px;
}

.icon-special-char:before {
  content: "Ω";
}

.icon-clear-format:before {
  content: "✕";
  font-weight: bold;
}

.icon-link:before {
  content: "🔗";
  font-size: 14px;
}

.icon-image:before {
  content: "🖼";
  font-size: 14px;
}

.icon-font-family:before {
  content: "A";
  font-weight: bold;
  font-size: 16px;
}

.icon-font-size:before {
  content: "T";
  position: relative;
  
  &:after {
    content: "T";
    position: absolute;
    left: 2px;
    top: 4px;
    font-size: 12px;
  }
}

.toolbar-select {
  width: 100px;
  margin-right: 6px;
  
  :deep(.el-input__inner) {
    height: 30px !important;
    line-height: 30px !important;
    padding: 0 8px !important;
    font-size: 12px !important;
  }
}

.toolbar-color-picker {
  height: 30px;
  width: 30px;
  margin-right: 6px;
  
  :deep(.el-color-picker__trigger) {
    width: 30px;
    height: 30px;
  }
}

.table-grid {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.table-grid-row {
  display: flex;
  gap: 2px;
}

.table-grid-cell {
  width: 20px;
  height: 20px;
  border: 1px solid #ddd;
  cursor: pointer;
  
  &:hover {
    background-color: #1e88e5;
    border-color: #1e88e5;
  }
}

.table-size-hint {
  text-align: center;
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

.special-chars-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 5px;
}

.char-btn {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ddd;
  background: #fff;
  cursor: pointer;
  font-size: 16px;
  
  &:hover {
    background-color: #f5f7fa;
    border-color: #c0c4cc;
  }
}

/* 字体选择面板样式 */
.font-family-panel {
  max-height: 200px;
  overflow-y: auto;
}

.font-option {
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 4px;
  
  &:hover {
    background-color: #f5f7fa;
  }
}

/* 字号选择面板样式 */
.font-size-panel {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 5px;
}

.size-option {
  padding: 8px;
  text-align: center;
  cursor: pointer;
  border-radius: 4px;
  
  &:hover {
    background-color: #f5f7fa;
  }
}
</style>